package my.story;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.story.db.DBUtils;

/**
 * Servlet implementation class PicInfoEdit
 */
@WebServlet("/PicInfoEdit")
public class PicInfoEdit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PicInfoEdit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String picId = request.getParameter("picId");
		StringBuilder sql = new StringBuilder("select * from piccomment ");
		String picName = "";
		String comment = "";
		long nextId = 0;
		long id = 0;
		Statement st = null;
		ResultSet rs = null;
		Connection conn = DBUtils.getConnection();
		if(picId!=null && !"".equals(picId)){
			id = Long.valueOf(picId);
			String preComment = request.getParameter("picComment");
			String updateSql = "update piccomment set comment = '"+preComment+"' where id="+id;
			try {
				st = conn.createStatement();
				st.execute(updateSql);
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				DBUtils.release(st);
			}
		}
		
		
		
		sql.append("where id=").append(id+1);
		
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql.toString());
			if(rs.next()){
				nextId = rs.getLong(1); 
				picName = rs.getString(2);
				comment = rs.getString(3);
				request.getSession().setAttribute("imageId", nextId);
				request.getSession().setAttribute("imageName", picName);
				request.getSession().setAttribute("comment", comment);
				response.sendRedirect("edit.jsp");
			}else{
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write("编辑完成了。。。<p><a href=\"Show\">显示效果</a><p><a href=\"PicInfoEdit\">重新编辑</a>");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DBUtils.release(rs);
			DBUtils.release(st);
			DBUtils.release(conn);
		}
		
		
	}

}
